package com.rich.dmr.receiver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Build;
import android.util.Log;

import com.rich.dmr.DmrApplication;
import com.rich.dmr.service.DmrService;
import com.rich.dmr.service.DmrUtilJob;
import com.rich.dmr.ui.activity.MainActivity;
import com.rich.dmr.utils.SoundPoolUtils;

import java.util.List;

import rich.dmr.DmrManager;

public class DmrBroadcastReceiver extends BroadcastReceiver {
    private String TAG = "rich---DmrBroadcastReceiver";
    private static DmrManager mDmrManager;
    private static SharedPreferences mSp;
    private static long timeDown = System.currentTimeMillis();
    //private static long timeUp = System.currentTimeMillis();

    @SuppressLint("WrongConstant")
    @Override
    public void onReceive(Context context, Intent intent) {
        if (mDmrManager == null) {
            mDmrManager = (DmrManager) context.getSystemService("dmrservice");
        }

        if (mSp == null) {
            mSp = context.getSharedPreferences("rich_dmr", Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor mEditor = mSp.edit();
        timeDown = mSp.getLong("timeDown", System.currentTimeMillis() - 2000);
        //timeUp = mSp.getLong("timeUp", System.currentTimeMillis() - 2000);
        long temp = System.currentTimeMillis();
        long diff = temp - timeDown;
        if ("android.intent.action.PTT.down".equals(intent.getAction())) {
            if (mDmrManager.getMode() == 0) {
                if (diff > 800) {
                    if (mDmrManager != null) {
                        Log.d(TAG, "android.intent.action.PTT.down");
                    /*if (!isAppIsInBackground(context)) {
                        //mDmrManager.sendDmrPTT(true);
                        //abortBroadcast();
                        Log.d(TAG, "isAppIsInBackground false");
                    } else {
                        Log.d(TAG, "isAppIsInBackground true");
                        if (isMobileDataEnable(context) || isWifiDataEnable(context)) {
                            Log.d(TAG, "network available.");
                        } else {
                            Log.d(TAG, "network unavailable.");
                            //mDmrManager.sendDmrPTT(true);
                            //abortBroadcast();
                        }
                    }*/
                        mDmrManager.sendDmrPTT(true);
                        abortBroadcast();
                    }
                    timeDown = System.currentTimeMillis();
                    mEditor.putLong("timeDown", timeDown);
                    mEditor.apply();

                } else if(diff < 0){
                    timeDown = System.currentTimeMillis();
                    mEditor.putLong("timeDown", timeDown);
                    mEditor.apply();
                    SoundPoolUtils.getInstance(context).playSoundErr();
                }else{
                    SoundPoolUtils.getInstance(context).playSoundErr();
                    Log.d(TAG, "SoundPoolUtils down");
                }
            }

        } else if ("android.intent.action.PTT.up".equals(intent.getAction())) {
            if (mDmrManager != null) {
                Log.d(TAG, "android.intent.action.PTT.up");
                    /*if (!isAppIsInBackground(context)) {
                        //mDmrManager.sendDmrPTT(false);
                        //abortBroadcast();
                        Log.d(TAG, "isAppIsInBackground false");
                    } else {
                        Log.d(TAG, "isAppIsInBackground true");
                        if (isMobileDataEnable(context) || isWifiDataEnable(context)) {
                            Log.d(TAG, "network available.");
                        } else {
                            Log.d(TAG, "network unavailable.");
                            //mDmrManager.sendDmrPTT(false);
                            //abortBroadcast();
                        }
                    }*/
                if (mDmrManager.getMode() == 0) {
                    mDmrManager.sendDmrPTT(false);
                    abortBroadcast();
                }
            }
        }else if("android.intent.action.KNOB_LONG_PRESS".equals(intent.getAction())){
            //bfp remove
           /* if(isAppIsInBackground(context)){
                Log.d(TAG, "android.intent.action.KNOB_LONG_PRESS");
                intent.setClass(context,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }*/
        }else if("android.intent.action.KNOB_TRIPLE_PRESS".equals(intent.getAction())){
            //bfp remove
            /*if(isServiceRunning(context)){
                Log.d(TAG, "android.intent.action.KNOB_TRIPLE_PRESS");
                mDmrManager.setMode(1);
                mSp.edit().putBoolean("shutdown_app", true).apply();
                context.stopService(new Intent(context, DmrService.class));
                DmrApplication.getInstance().exit();
                System.exit(0);
            }*/
        }else if("android.intent.action.OPEN_DMR_APP".equals(intent.getAction())){
            if(isAppIsInBackground(context)){
                Log.d(TAG, "android.intent.action.OPEN_DMR_APP");
                intent.setClass(context,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        }else if("android.intent.action.CLOSE_DMR_APP".equals(intent.getAction())){
            if(isServiceRunning(context)){
                Log.d(TAG, "android.intent.action.CLOSE_DMR_APP");
                //mDmrManager.setMode(1);
                mSp.edit().putBoolean("shutdown_app", true).apply();
                context.stopService(new Intent(context, DmrService.class));
                DmrApplication.getInstance().exit();
                System.exit(0);
            }
        }else if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
            DmrUtilJob.scheduleJob(context);
            mEditor.putLong("timeDown",  System.currentTimeMillis());
            mEditor.apply();
        }else if("android.intent.action.TIMEZONE_CHANGED".equals(intent.getAction())){
            Log.d(TAG, "android.intent.action.TIMEZONE_CHANGED");
            mEditor.putLong("timeDown",  System.currentTimeMillis());
            mEditor.apply();
        }
    }


    private boolean isServiceRunning(Context context){
        ActivityManager mAm = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
        String mServiceName = DmrService.class.getName();
        for(ActivityManager.RunningServiceInfo runningService :
                mAm.getRunningServices(Integer.MAX_VALUE)){
            if(mServiceName.equals(runningService.service.getClassName())){
                Log.i(TAG, "#####Service is Running");
                return true;
            }
        }
        Log.i(TAG, "#####Service is not Running");
        return false;
    }

    private boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

    public static boolean isMobileDataEnable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isMobileDataEnable = false;
        isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        return isMobileDataEnable;
    }


    public static boolean isWifiDataEnable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isWifiDataEnable = false;
        isWifiDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        return isWifiDataEnable;
    }


}
